package com.shundr.shipper.route;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.shundr.shipper.R;
import com.shundr.shipper.base.BaseActivity;
import com.shundr.shipper.cargo.dao.CargoDao;
import com.shundr.shipper.common.dao.RouteDao;
import com.shundr.shipper.common.util.DialogUtil;
import com.shundr.shipper.common.util.PrefConstants;
import com.shundr.shipper.common.util.PrefUtils;
import com.shundr.shipper.common.util.ProgressDialogHelper;
import com.shundr.shipper.common.util.ToastHelper;
import com.shundr.shipper.common.view.DialogDisplay.OnDisplayListener;
import com.shundr.shipper.frame.constant.LContext;
import com.shundr.shipper.frame.http.LHttpRequest;
import com.shundr.shipper.route.http.RouteRequest;
import com.shundr.shipper.route.model.TruckerRouteInfo;

/**
 * 常跑路线管理 RouteSettingActivity
 * 
 * @author larry 2015-4-22 上午11:28:08
 * @version 1.0.0
 *
 */
public class RouteSettingActivity extends BaseActivity implements
		OnClickListener {
	private TextView tvNoRoute;
	private ToggleButton btnVoice, btnReceive;
	private ListViewForScrollView mListView;
	
	private LinearLayout mLayoutClear;

	private List<TruckerRouteInfo> mList = new ArrayList<TruckerRouteInfo>();
	private RouteSettingAdapter mAdapter;
	private int flag=0;
	
	private boolean isReceivered = true;
	private boolean isVoiced = true;
	
	private CargoDao mCargoDao;
	private RouteDao mRouteDao;

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case RouteRequest.GET_ROUTE_LIST_SUCCESSED:
					List<TruckerRouteInfo> infos = (List<TruckerRouteInfo>) msg.obj;
					if(infos!=null){
						mRouteDao.syncData(infos);
						mList.clear();
						mList.addAll(infos);
						if(infos.size()<=0){
							tvNoRoute.setVisibility(View.VISIBLE);
						}else{
							tvNoRoute.setVisibility(View.GONE);
						}
						mAdapter.notifyDataSetChanged();
					}
					break;
				case RouteRequest.DELETE_ROUTE_SUCCESSED:
					try {
//						TruckerRouteInfo routeInfo = mList.get(flag);
//						mCargoDao.deleteCargoByRoute(routeInfo.getCargoSrcCode(), routeInfo.getCargoDstCode());
						mList.remove(flag);
						if(mList.size() == 0){
							tvNoRoute.setVisibility(View.VISIBLE);
						}
						mAdapter.notifyDataSetChanged();
						new RouteRequest(mContext, mHandler).getRouteList();
					} catch (Exception e) {
						e.printStackTrace();
					}
					ToastHelper.toastShort(mContext, msg.obj.toString());
					break;
				case RouteRequest.DISABLE_ROUTE_SUCCESSED:
					ToastHelper.toastShort(mContext, "关闭监控货源");
					btnReceive.setChecked(false);
					PrefUtils.setPrefBoolean(mContext, PrefConstants.IS_RECEIVER_ON, false);
					break;
				case RouteRequest.ENABLE_ROUTE_SUCCESSED:
					ToastHelper.toastShort(mContext, "开启监控货源");
					btnReceive.setChecked(true);
					PrefUtils.setPrefBoolean(mContext, PrefConstants.IS_RECEIVER_ON, true);
					break;
				case LHttpRequest.REQUEST_FAILED:
					ToastHelper.toastShort(mContext, msg.obj.toString());
					break;
				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			ProgressDialogHelper.dismiss();
			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		tvTitle.setText("路线设置");
		setContentView(R.layout.activity_route_setting);
		btnVoice = (ToggleButton) findViewById(R.id.btn_set_voice);
		btnReceive = (ToggleButton) findViewById(R.id.btn_set_receive);
		tvNoRoute = (TextView) findViewById(R.id.tv_no_route);
		mLayoutClear = (LinearLayout)findViewById(R.id.layout_clear);
		mLayoutClear.setOnClickListener(this);
		mListView = (ListViewForScrollView) findViewById(R.id.lv_route_list_set);
		btnVoice.setOnClickListener(this);
		btnReceive.setOnClickListener(this);
		ProgressDialogHelper.show(mContext, "正在加载中...");
		new RouteRequest(mContext, mHandler).getRouteList();
		mAdapter=new RouteSettingAdapter();
		mListView.setAdapter(mAdapter);
		
		isReceivered = PrefUtils.getPrefBoolean(mContext, PrefConstants.IS_RECEIVER_ON, true);
		btnReceive.setChecked(isReceivered);
		
		isVoiced = PrefUtils.getPrefBoolean(mContext, PrefConstants.IS_TTS_ON, true);
		btnVoice.setChecked(isVoiced);
		mCargoDao = new CargoDao();
		mRouteDao = new RouteDao();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_set_voice:
			if(btnVoice.isChecked()){
				PrefUtils.setPrefBoolean(mContext, PrefConstants.IS_TTS_ON, true);
				LContext.isTtsOpened = true;
				ToastHelper.toastShort(mContext, "开启语音播报");
			}else{
				PrefUtils.setPrefBoolean(mContext, PrefConstants.IS_TTS_ON, false);
				LContext.isTtsOpened = false;
				ToastHelper.toastShort(mContext, "关闭语音播报");
			}
			break;
		case R.id.btn_set_receive:
			if(btnReceive.isChecked()){
				new RouteRequest(mContext, mHandler).enableRoute();
			}else{
				new RouteRequest(mContext, mHandler).disableRoute();
			}
			break;
		case R.id.layout_clear:
			DialogUtil.noticeAlertDialog(mContext, "操作", "确认清空本地货源吗？",
					new OnDisplayListener() {

						@Override
						public void confirm() {
							try {
								if(mCargoDao == null){
									mCargoDao = new CargoDao();
								}
								ProgressDialogHelper.show(mContext, "正在清空本地货源...");
								mCargoDao.clear();
								mHandler.postDelayed(new Runnable() {
									
									@Override
									public void run() {
										ProgressDialogHelper.dismiss();
										ToastHelper.toastShort(mContext, "清空完成");
									}
								}, 2000);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}

						@Override
						public void cancel() {

						}
					});
			break;
		default:
			break;
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_confirm, menu);
		menu.getItem(0).setTitle("添加");
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_confirm:
			Intent start = new Intent(mContext, RouteAddActivity.class);
			startActivityForResult(start, 500);
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 500:
			ProgressDialogHelper.show(mContext, "正在加载中...");
			new RouteRequest(mContext, mHandler).getRouteList();
			break;
		default:
			break;
		}
	}

	class RouteSettingAdapter extends BaseAdapter {

		public RouteSettingAdapter() {

		}

		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			LayoutInflater layoutInflater = LayoutInflater.from(mContext);
			final TruckerRouteInfo ur = mList.get(position);
			if (convertView == null) {
				convertView = layoutInflater.inflate(R.layout.item_route_setting, parent, false);
			}
			ViewHodler vh = (ViewHodler) convertView.getTag();
			if (vh == null) {
				vh = new ViewHodler();
				vh.tvSrc = (TextView) convertView
						.findViewById(R.id.tv_set_route_src);
				vh.tvDest = (TextView) convertView
						.findViewById(R.id.tv_set_route_dest);
				vh.ivDelete = (ImageView) convertView
						.findViewById(R.id.iv_set_delete);
				convertView.setTag(vh);
			}
			try {
				vh.tvSrc.setText(ur.getCargoSrcPlace());
				vh.tvDest.setText(ur.getCargoDstPlace());
				vh.ivDelete.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						flag=position;
						DialogUtil.noticeAlertDialog(mContext, "删除", "是否确定删除此路线？", new OnDisplayListener() {
							@Override
							public void confirm() {
								ProgressDialogHelper.show(mContext, "正在删除中...");
								if(ur.getId()!=null){
									new RouteRequest(mContext, mHandler).deleteRoute(ur.getId()+"");
								}	
							}
							@Override
							public void cancel() {}
						});
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}

		class ViewHodler {
			TextView tvSrc;
			TextView tvDest;
			ImageView ivDelete;
		}
	}

}
